<?php

require_once '../../ConfigurationFactory.php';
require_once APP_UTILS . DS . 'Util.php';

/**
 * Valorizza in automatico un oggetto
 *
 * @author fabio
 */
class ValueEntity {

    private static $returnValue;

    /**
     *
     * @param <type> $entity oggetto da valorizzare
     * @param <type> $rs recordset riga query
     * @return <type>
     */
    public function  __construct($entity, $rs) {
        $reflect = new ReflectionClass($entity);

        //Setto il camp id che deve essere sempre presente
        $id = $rs['id'];
        //Se è un intero lo converto in itero
        if(is_numeric($id))
            $id = intval($rs['id']);
        
        $entity->setId($id);
         
        $props   = $reflect->getProperties(ReflectionProperty::IS_PRIVATE);

        foreach ($props as $prop) {
 
            $propertyName = $prop->getName();
            $columName = Util::splitAndCombineAtUpperCase ($prop->getName());
            $propertyValue = null;

            //Individuo il valore della property
            $methodName = 'set' . ucfirst($propertyName);
            
            if (method_exists($entity, $methodName) &&
                array_key_exists($columName, $rs)) {

                $reflection_method = $reflect->getMethod("$methodName");
                $reflection_method->setAccessible(true);

                $value = utf8_encode($rs[$columName]);
                
                if(is_numeric($value) && is_int($value))
                    $value = intval($value);
                else if (is_numeric($value) && is_float($value))
                    $value = floatval($value);
                else if (is_bool($value))
                    $value = boolval($value);

                $result = $reflection_method->invoke($entity, $value);

            } 

        }

        self::$returnValue = $entity;
      
    }

    public function getEntityValorized() {
        return self::$returnValue;
    }

}
?>
